import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { todoCheckAll } from '../../store/actions/todo'
import TodoItem from '../TodoItem'

export default function TodoMain() {
  const renderLists = useSelector(state => {
    const ac = state.filter.active
    if (ac === 'active') {
      return state.todo.filter(item => !item.done)
    } else if (ac === 'completed') {
      return state.todo.filter(item => item.done)
    } else {
      return state.todo
    }
  })
  const lists = useSelector(state => state.todo)
  const currState = lists.every(item => item.done)
  const dispatch = useDispatch()

  function checkAll() {
    // 当前状态基础取反
    dispatch(todoCheckAll(!currState))
  }

  return (
    <section className="main">
      <input id="toggle-all" className="toggle-all" type="checkbox" />
      <label htmlFor="toggle-all" onClick={checkAll}>
        Mark all as complete
      </label>
      <ul className="todo-list">
        {renderLists.map(item => {
          return <TodoItem item={item} key={item.id}></TodoItem>
        })}
      </ul>
    </section>
  )
}
